package no.uio.inf5750.j2mewsclient;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Gauge;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class SimpleMIDlet extends MIDlet implements CommandListener, IResultReceiver {

    private Command cmdExit, cmdConvert;

    private Display display;

    private Form form;

    private TextField fieldCelsius;
    private StringItem stringResult;
    private Gauge gaugeProgress;

    private final String MESSAGE_READY = "Enter a value and press Convert.";

    public void startApp() throws MIDletStateChangeException {

        display = Display.getDisplay(this);

        form = new Form("Simple");
        form.setCommandListener(this);

        // Set up exit button
        cmdExit = new Command("Exit", Command.EXIT, 0);
        form.addCommand(cmdExit);

        // Add some text
        form.append("Hello j2me\n");

        // Add textfield (with label) for temperature
        fieldCelsius = new TextField("Temperature (C):", "0", 10, TextField.DECIMAL);
        form.append(fieldCelsius);

        // Add a gauge for indicating activity
        gaugeProgress = new Gauge(MESSAGE_READY, false, Gauge.INDEFINITE, Gauge.CONTINUOUS_IDLE);
        form.append(gaugeProgress);

        // Add a status string
        stringResult = new StringItem("Result:", "No value yet.");
        form.append(stringResult);

        // Add convert command
        cmdConvert = new Command("Convert", Command.OK, 0);
        form.addCommand(cmdConvert);

        // Display the form
        display.setCurrent(form);
    }
    public void pauseApp() {

    }

    public void destroyApp(boolean unconditional) throws MIDletStateChangeException {
        notifyDestroyed();
    }

    /*
     * Callback to handle commands from the user.
     */
    public void commandAction(Command c, Displayable d) {
        if (d == form) {
            if (c == cmdExit) {
                try {
                    destroyApp(true);
                } catch (MIDletStateChangeException e) {
                    showException(e);
                }
            } else if (c == cmdConvert) {
                initiateConversion();
            }
        }
    }

    /*
     * Spawns a Thread which talks to the webservice. Returns immediately.
     */
    private void initiateConversion() {

        setState("Please wait...", "Working...", Gauge.CONTINUOUS_RUNNING);

        String celsius = fieldCelsius.getString();
        new ConvertTemperatureThread().convert(celsius, this);
    }

    /*
     * Implementation of IResultReceiver.addResult(). Callback used to add a
     * result of a operation.
     */
    public void addResult(Object resultID, Object result) {
        if (result instanceof String) {
            setState(resultID + " C = " + result + " F", MESSAGE_READY, Gauge.CONTINUOUS_IDLE);
        } else if (result instanceof Exception) {
            setState("Error: " + result, MESSAGE_READY, Gauge.CONTINUOUS_IDLE);
        }
    }

    /*
     * Updates the result string and activity indicator. Synchronized in case
     * several threads invokes it (typically via addResult()).
     */
    public synchronized void setState(String result, String progressLabel, int progressState) {
        stringResult.setText(result);
        gaugeProgress.setLabel(progressLabel);
        gaugeProgress.setValue(progressState);
    }

    /*
     * Displays an error-screen.
     */
    public void showException(Exception e) {
        Alert alert = new Alert("Error");
        alert.setString(e.getMessage());
        alert.setType(AlertType.ERROR);
        alert.setTimeout(Alert.FOREVER);
        display.setCurrent(alert);
    }

}
